package in.muton.edushare.components.autocomplete;

import in.muton.edushare.EduShareSession;
import in.muton.edushare.components.autocomplete.api.MainInviter;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.wicket.ajax.AbstractDefaultAjaxBehavior;
import org.apache.wicket.ajax.AjaxRequestTarget;
import org.apache.wicket.markup.html.IHeaderResponse;
import org.apache.wicket.markup.html.form.TextArea;
import org.apache.wicket.markup.html.form.TextField;

public class EdushareAutoCompleteBehaviour extends AbstractDefaultAjaxBehavior {
	private static final long serialVersionUID = 8252270158543901139L;
	public static final Log log = LogFactory.getLog(EdushareAutoCompleteBehaviour.class);
	private TextField<String> field = null;
	private TextArea<String>  area = null;
	private String wicketVarName = "jQuery_Wicket_data";
	private MainInviter inviter;
	
	public EdushareAutoCompleteBehaviour(TextField<String> field){
		inviter = new MainInviter(EduShareSession.get().getSessionORMInterface());
		this.field = field;
	}
	
	public EdushareAutoCompleteBehaviour(TextArea<String> area){
		inviter = new MainInviter(EduShareSession.get().getSessionORMInterface());
		this.area = area;
	}
	
	@Override
	protected void respond(AjaxRequestTarget arg0) {
		String suffix = "";
		if(field != null)
			suffix = field.getRequest().getParameter("suffix");
		else
			suffix = area.getRequest().getParameter("suffix");
		String result = inviter.getOptions(suffix);
		result = '"'+result+'"';
		log.debug("Suffix is "+ suffix);
		log.debug("JSON result = "+result);
		arg0.appendJavascript(";"+wicketVarName + " = "+result+";");
	}
	
	@Override
	public void renderHead(IHeaderResponse response){
		super.renderHead(response);
		response.renderJavascript("var " + wicketVarName + ";", wicketVarName);
	}
}
